<!-- 提交订单 -->
<template>
	<view class="order">
		<view class="order_content pr">
			<view class="list">
				<view class="order_top df" @tap.stop="jump(address_url)">
					<view class="top_card_left1" v-if="showSelect">
						<view class="top_card_place">请选择收货地址</view>
					</view>
					<view class="top_card_left" :index="index" @isUserinfo="isUserinfo" v-if="!showSelect">
						<span v-if="selected.is_default">{{type}}</span>
						<p class="dib" :class="selected.is_default == 1 ? 'changeTop1' : 'changeTop'">
							{{selected.address}}</p>
						<view class="top_card_room"></view>
						<view class="top_card_user dib">用户ID</view>
						<view class="top_card_phone dib">{{selected.mobile}}</view>
					</view>
					<image class="x-f" :src="arrow_right"></image>
				</view>
				<view class="order_card df" :index="index" v-for="(item, index) in cart_group" :key="item.id"
					@click="changePoint(item,index)">
					<view class="order_left tc pr df">
						<view class="myteam pa x-c tc" v-if="item.is_group">拼团</view>
						<image :src="item.pic_url" mode="aspectFit" class="order_photo"></image>
					</view>
					<view class="order_right pr di">
						<view class="order_title">
							<p>{{ item.spu_name }}</p>
							<view class="standards x-bc">
								<view class="norms">{{item.display_string}}</view>
								<view class="value">*{{item.sale_count}}</view>
							</view>
							<view class="pay_title tr">
								<span>应付：<span style="color: #FF2D1B;">{{item.unit_points || '0'}}</span>积分</span><span
									class="consume_amount">+¥
									<span style="color: #FF2D1B;">{{item.unit_amount || '0'}}</span>元</span>
							</view>
						</view>
					</view>
				</view>
				<view class="order_middle">
					<view class="middle_first x-f">
						<p>邮费</p>
						<input type="text" value="" placeholder="包邮" :disabled="true" />
					</view>
				</view>
				<view class="middle_two x-f">
					<p>备注信息</p>
					<input type="text" v-model="orderInfo.remark" placeholder="请输入备注信息" />
				</view>
				<view class="middle_User x-f">
					<p>员工码</p>
					<input type="text" v-model="orderInfo.code" value="orderInfo.code" placeholder="请输入员工码" />
				</view>
				<!-- 有优惠券 -->
				<view class="middle_coupons x-bc pr" v-if="couponsDetail.length" @tap.stop="jump(coupons)">
					<view class="middle_coupon_box">
						<image src="/static/image/card10.png" />
						<p>优惠券</p>
					</view>
					<view class="right ">￥{{actPoint}}积分</view>
				</view>
				<!-- 无优惠券 -->
				<view class="middle_coupons x-bc pr" v-if="!couponsDetail.length">
					<view class="middle_coupon_box">
						<image src="/static/image/card10.png" />
						<p>优惠券</p>
					</view>
					<view class="right x-c ">暂无可用优惠券</view>
				</view>
			</view>
			<view class="order_bottom x-bc pf">
				<view class="x-c">
					<span class="sumScore1">实付：</span><span
						style="color: #FF2D1B; font-size: 26rpx;">{{sumScore || '0'}}</span>积分<span class="money">+
						¥ <span style="color: #FF2D1B; font-size: 26rpx;">{{money || '0'}}</span>元</span>
				</view>
				<view class="order_bottom_btn x-bc">
					<view class="swap x-c" @tap.stop="jumpPay(pay)">
						<view class="swap_text">立即支付</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 提示现金未支付 -->
		<view class="finish_box pf" v-if="finish_status">
			<view class="card pa">
				<view class="name x-c">温馨提示</view>
				<view class="text x-c">积分付款成功，现金未支付，是否支付现金</view>
				<view class="btn x-ac">
					<view class="cancel" @click="cancel">取消</view>
					<view class="finally" @click="finall">确定</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	import md5 from 'js-md5';
	import number from 'pages/cart_index/components/numberBox.vue'
	export default {
		components: {
			number
		},
		data() {
			return {
				coupons: '/pages/order/choseCoupons/index', // 优惠券跳转地址
				type: '默认', // 默认地址
				pay: '/pages/order/pay/index', // 支付页面跳转地址
				address_url: '/pages/user/info/address/index', // 地址页面跳转地址
				checked: false, // 选择状态
				sum_list: [], // 选择列表
				sumScore: 0, // 总积分
				address: [], // 地址信息
				arrow_right: this.imgUrl + 'arrow_right.png', // 右箭头
				orderInfo: { // 备注 - 员工码
					remarks: '',
					code: ''
				},
				showSelect: false, // 判断是否收货地址提示
				place: {}, // 地址信息
				actPoint: 0, // 当前积分
				maxPoint: 0, // 最大积分
				infoCoupons: {
					key: ''
				}, // 优惠券信息
				indexList: [], // 最大积分列表下标
				showselected: false, // 是否显示优惠券
				finish_status: false, // 现金未支付
				subObj: {}, // 提交消费
				allEqual: false, // 判断是否全等
				pay_money: {}, // 返回积分订单信息
				isClick: 1 // 应许点击一次
			};
		},
		computed: {
			...mapState({
				cart_group: state => state.order.order, // 订单信息
				sum: state => state.cart.sum, // 总积分
				money: state => state.cart.money, // 总金额
				userinfo: state => state.address.list, // 用户信息
				selected: state => state.address.selected, // 选择的地址
				couponsPoint: state => state.order.couponsPoint, // 优惠券积分
				couponsDetail: state => state.order.canUser, // 可以优惠券
				couponsInfo: state => state.order.coupons, // 优惠券信息
				credit: state => state.order.credit, // 选择优惠券信息
				isUseFit: state => state.order.isUseFit, // 使用优惠券信息
				buttonType: state => state.order.type, // 订单类型状态
				order: state => state.order.order, // 订单列表
				order_group_no: state => state.goods.groupKey, // 参与团购
				pointList: state => state.order.pointList, // 积分列表
				canUser: state => state.order.canUser, // 可以优惠券
			})
		},
		// 该页面显示时。
		onShow() {
			this.isClick = 1;
			this.place = this.selected
			// 判断是否有地址
			this.isObj();
			// 计算扣除优惠券，商品积分
			this.goodSum();
		},
		mounted() {
			// let sign = md5('1111111111aaaaaaaa')
			// console.log(sign,'sign')
			// 判断当没有使用优惠券时，清除订单的key
			if (this.credit == null) {
				this.cart_group.forEach(item => {
					item.coupon_no = ''
				})
			}
			// 判断最大积分是否大于优惠券
			let arr = this.canUser.filter(item => {
				return item.points <= this.maxPoint
			})
			this.$store.dispatch('order/get_canUser', arr)
			// 判断是否有优惠券信息
			if (this.credit != null) {
				let points = this.maxPoint - this.couponsPoint
				this.cart_group.forEach(item => {
					if (item.consume_points != points) {
						item.coupon_no = '';
					}
					if (item.consume_points == points) {
						item.coupon_no = this.credit.key;
					}
				})
			}
			// 判断是否参与拼团
			if (this.buttonType == 'group') {
				this.cart_group[0].is_group = 1;
			} else {
				this.cart_group[0].is_group = 0;
			}
			this.sumScore = this.sum;
			if (this.buttonType == 'exchange') {
				this.subObj.amount = this.order[0].consume_amount
				this.subObj.points = this.order[0].consume_points
			}
			if (this.buttonType == 'group') {
				this.subObj.amount = 0
				this.subObj.points = this.order[0].consume_points
			}
			// 使用优惠券，修改提交信息
			if (this.credit != null && this.isUseFit) {
				this.subObj.points = this.order[0].consume_points - this.credit.points
				this.sumScore = this.sum - this.credit.points
			}
			this.isObjSelected();
			this.actPoint = this.couponsPoint
			this.defaultAddress();
			if (this.couponsInfo != undefined || this.couponsInfo != null) {
				this.infoCoupons = this.couponsInfo
			}
		},
		onUnload() {
			// 回复订单积分价格
			// 如果从购物车下单，判断优惠券扣除
			if (this.buttonType == 'cart') {
				for (let i in this.cart_group) {
					this.cart_group[this.indexList[0]].consume_points = this.cart_group[this.indexList[0]].consume_points +
						this.couponsPoint;
					return;
				}
			}
			// 更新订单
			this.$store.dispatch('order/get_order', this.cart_group)
			// 清理优惠券使用状态
			this.$store.dispatch('order/get_isUseFit', false)
			// 清理优惠券信息
			this.$store.dispatch('order/get_credit', null)
			// 清理优惠券积分
			this.$store.dispatch('order/get_couponsPoint', 0);
			// 清理优惠券
			this.$store.dispatch('order/get_coupons', null)
			// 清理优惠券下标
			this.$store.dispatch('order/get_selectAct', -1)
			// 将团ID清空 存放至VUEX中
			this.$store.dispatch('goods/get_groupKey', '');
			// 更新购物车
			this.$store.dispatch('cart/get_cart_group');
		},
		methods: {
			// 判断积分列表相等
			isAllEqual(array) {
				if (array.length > 0) {
					return !array.some(function(value, index) {
						return value !== array[0];
					});
				} else {
					return true;
				}
			},
			// 计算积分减法
			calcReduce(i) {
				if (this.cart_group[i].consume_points == this.maxPoint) {
					this.cart_group[i].consume_points = this.cart_group[i].consume_points - this.couponsPoint
					if (this.credit != null) {
						this.cart_group[i].coupon_no = this.credit.key
					}
				}
			},
			// 计算积分加法
			calcAdd(i) {
				if (this.cart_group[i].consume_points == this.maxPoint) {
					this.cart_group[i].consume_points = this.cart_group[i].consume_points + this.couponsPoint
				}
			},
			// 计算扣除优惠券，商品积分
			goodSum() {
				let pointList = [];
				for (let i in this.cart_group) {
					pointList.push(this.cart_group[i].consume_points)
				}
				this.maxPoint = Math.max(...pointList)
				// 提交积分列表
				this.$store.dispatch('order/get_pointList', pointList)
				this.allEqual = this.isAllEqual(pointList)
				this.$store.dispatch('order/get_maxPoint', this.maxPoint)
				// 购物车列表最大积分相等时，扣除第一个积分
				// 如果积分最大的值一样，则扣除相同最大积分的第一个积分
				for (let i in this.cart_group) {
					if (this.cart_group[i].consume_points == this.maxPoint) {
						this.indexList.push(i)
					}
				}
				let w = this.indexList[0]
				// 如果从购物车下单，判断优惠券扣除
				if (this.buttonType == 'cart') {
					for (let i in this.cart_group) {
						// 判断是否全部积分一致
						if (this.allEqual) {
							if (this.isUseFit) {
								this.calcReduce(0);
							}
						} else {
							// 全部积分一致不相等，扣除最大积分
							if (this.indexList.length == 1) {
								if (this.credit != null && this.isUseFit) {
									this.cart_group[w].coupon_no = this.credit.key
								}

								this.calcReduce(this.indexList[0]);
							} else {
								// 当积分不全部相等，且有多个最大积分，则取第一个最大积分
								if (this.credit != null && this.isUseFit) {
									this.cart_group[this.indexList[0]].coupon_no = this.credit.coupon_no
								}
								this.calcReduce(this.indexList[0]);
							}
						}
					}
				}
			},
			// 判断是否对象为空
			isObj() {
				if (Object.keys(this.place).length == 0) {
					this.showSelect = true
				} else {
					this.showSelect = false
				}
			},
			// 判断选择地址是否为空
			isObjSelected() {
				if (Object.keys(this.selected).length == 0) {
					this.showselected = true
				} else {
					this.showselected = false
				}
			},
			// 筛选默认地址
			defaultAddress() {
				if (this.showselected) {
					this.userinfo.map((item, index) => {
						if (item.is_default) {
							this.$store.dispatch('address/get_selected', item)
							this.place = item
						} else {
							// 如果没有默认，则显示请选择收货地址
							this.place = this.selected
						}
						this.isObj();
					})
				}

			},
			// 跳转信息
			jump(path, params) {
				if (this.buttonType !== 'cart') {
					this.$Router.push({
						path: path,
						params: params
					})
				} else {
					this.$Router.replace({
						path: path,
						params: params
					})
				}
			},
			// 取消
			cancel() {
				this.finish_status = false;
				this.$Router.replace({
					path: '/pages/user/order/index'
				})
			},
			// 完成
			finall() {
				if (this.pay_money.data.prepay_id != null && this.pay_money.status) {
					// 测试支付通知
					this.$api('payNotify', {
						pay_no: this.pay_money.data.pay_no,
						pay_time: this.pay_money.data.submit_time
					}).then(res => {
						this.finish_status = false;
						if (res.status) {
							this.$Router.replace({
								path: '/pages/order/pay/index'
							})
						}
					})
				}
			},
			// 立即付款
			jumpPay(path, params) {
				// 判断送货地址对象为空
				let selectedNo = (JSON.stringify(this.selected) == "{}")
				if (selectedNo) {
					this.$tools.toast('请填写收货地址')
					return;
				}
				// 判断点击了一次
				if (this.isClick != 1) return;
				if (this.isClick) {
					this.isClick = 0;
					// 添加订单
					/**
					 * 构造请求参数
					 * @total_amount: 支付金额
					 * @total_points: 支付积分
					 * @staff_no:  员工码
					 * @order_item: 购买商品列表
					 * @order_group_no: 参与拼团的编号
					 * @remark: 备注
					 * @address_info: 收件人地址
					 */
					let obj = {
						total_amount: this.money,
						total_points: this.sumScore,
						staff_no: this.orderInfo.code,
						order_item: [{
							sku_id: this.order[0].sku_id,
							sale_count: this.order[0].sale_count,
							consume_points: this.subObj.points,
							consume_amount: this.subObj.amount,
							coupon_no: this.infoCoupons.key,
						}, ],
						order_group_no: this.order_group_no,
						remark: this.orderInfo.remark,
						address_info: {
							name: this.selected.name,
							mobile: this.selected.mobile,
							address: this.selected.address,
						}
					}
					if (this.buttonType == 'group') {
						this.$store.dispatch('cart/get_sum', 0)
						this.$api('createGroup', obj).then(res => {
							let arr = res;
							if (arr.status) {
								this.$store.dispatch('order/get_pay', arr.data)
								this.$Router.push({
									path: '/pages/order/pay/index',
									query: {
										id: arr.data.order_no
									}
								})
								this.$store.dispatch('cart/get_count', 0)
								// 将团ID清空 存放至VUEX中
								this.$store.dispatch('goods/get_groupKey', '');
							}
							this.isClick = 1;
						}).catch(e => {
							// 将团ID清空 存放至VUEX中
							this.$store.dispatch('goods/get_groupKey', '');
							this.isClick = 1;
						})
					}
					if (this.buttonType == 'exchange') {
						// 提交订单
						let newArr = JSON.parse(JSON.stringify(this.order)) //数组是引用类型, 深拷贝一下
						newArr.map(e => {
							delete e.checked
							delete e.display_string
							delete e.points
							delete e.shop_id
							delete e.show
							delete e.spu_id
							delete e.spu_name
							delete e.pic_url
						}) //然后删除属性title
						this.$api('ordercreate', obj).then(res => {
							console.log(res, '支付111')
							let arr = res;
							this.pay_money = res
							if (arr.status) {
								if (res.data.prepay_package == null) {
									console.log(res, '支付222')
									this.$Router.push({
										path: '/pages/order/pay/index',
									});
								} else {
									console.log(res, '支付333')
									// this.finish_status = true;
									let obj = res.data.prepay_package
									console.log(obj,'obj')
									wx.requestPayment({
										"timeStamp": obj.timeStamp,
										"nonceStr": obj.nonceStr,
										"package": obj.package,
										"signType": obj.signType,
										"paySign": obj.paySign,
										"success": function(res) {
											console.log(res, '支付成功')
											this.$Router.replace({
												path: '/pages/order/pay/index'
											})
										},
										"fail": function(res) {
											console.log(res, '支付失败')
										},
										"complete": function(res) {
											console.log(res, '支付complete')
										}
									})
								}
								this.$store.dispatch('order/get_pay', arr.data)
								this.$store.dispatch('cart/get_count', 0)
							}
							this.isClick = 1;
						}).catch(e => {
							this.isClick = 1;
						})
						this.$store.dispatch('cart/get_sum', 0)
					}
					if (this.buttonType == 'cart') {
						// 提交订单
						let newArr = JSON.parse(JSON.stringify(this.order)) //数组是引用类型, 深拷贝一下
						newArr.map(e => {
							delete e.checked
							delete e.display_string
							delete e.points
							delete e.shop_id
							delete e.show
							delete e.spu_id
							delete e.spu_name
							delete e.pic_url
							delete e.unit_amount
							delete e.unit_points
						}) //然后删除属性title

						obj.order_item = newArr;
						this.$api('ordercreate', obj).then(res => {
							let arr = res
							this.pay_money = res
							if (arr.status) {
								for (let i in this.order) {
									this.order[i].checked = false;
								}
								// 提交支付消息通知信息
								if (res.data.prepay_id == null) {
									this.$Router.push({
										path: '/pages/order/pay/index',
									});
								} else {
									// this.finish_status = true;
									let obj = res.data.prepay_package
									console.log(obj,'obj')
									wx.requestPayment({
										"timeStamp": obj.timeStamp,
										"nonceStr": obj.nonceStr,
										"package": obj.package,
										"signType": obj.signType,
										"paySign": obj.paySign,
										"success": function(res) {
											console.log(res, '支付成功')
											this.$Router.replace({
												path: '/pages/order/pay/index'
											})
										},
										"fail": function(res) {
											console.log(res, '支付失败')
										},
										"complete": function(res) {
											console.log(res, '支付complete')
										}
									})
									this.sumScore = 0;
									this.$store.dispatch('order/get_order', null)
									this.$store.dispatch('cart/get_sum', 0)
									this.$store.dispatch('cart/get_money', 0)
									this.$store.dispatch('cart/get_count', 0)
								}
								this.$store.dispatch('order/get_pay', arr.data)
								this.$store.dispatch('cart/get_count', 0)
							}
							this.isClick = 1;
						}).catch(e => {
							this.isClick = 1;
						})
					}
				}
			},
		},
	};
</script>
<style scoped lang='scss'>
	@import "./index.scss";
</style>
